package com.itshidu.game.filter;

import com.itshidu.game.entity.Hero;
import com.itshidu.game.entity.User;
import com.itshidu.game.mapper.HeroMapper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter(urlPatterns={
        "/my/info",
        "/my/equipment",
        "/my/items",
        "/my/skill",
        "/game/practice",
        "/game/practice/start",
        "/game/*"
})
public class HeroFilter implements Filter {

    @Autowired
    HeroMapper heroMapper;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("验证是否已经选择角色");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        Hero hero = (Hero) session.getAttribute("current-hero");
        if (hero == null) {
            response.sendRedirect(request.getContextPath()+"/my/hero");
            return;
        }
        Hero dbHero = heroMapper.selectById(hero.getId());
        if (dbHero == null) {
            response.sendRedirect(request.getContextPath()+"/my/hero");
            return;
        }

        filterChain.doFilter(request,response);
    }
}
